<template>
  <div>
    <a-card class="card-header">
      <a-form-model ref="ruleForm" :model="model" :rules="rules">
        <a-form-model-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="备料单号"
          prop="pickListNum"
          hasFeedback
          style="width: 33%;float: left;"
        >
          <a-input
            placeholder="请输入备料单号"
            v-model.trim="model.pickListNum"
          />
        </a-form-model-item>

        <a-form-model-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="仓库"
          hasFeedback
          prop="wareHouseId"
          style="width: 33%;float: left;"
        >
          <a-select v-model.trim="model.wareHouseId" placeholder="请选择仓库">
            <a-select-option
              v-for="item in wareHouseList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.wareHouseName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="加工单"
          hasFeedback
          prop="worksheetNum"
          style="width: 33%;float: left;"
        >
          <a-select
            :disabled="disabled"
            :open="false"
            :defaultOpen="false"
            mode="multiple"
            :allowClear="true"
            placeholder="加工单"
            v-model.trim="model.worksheetId"
            @dropdownVisibleChange="handleDepar"
            @change="handleDeparChange"
          >
            <a-select-option
              v-for="item in tableUserOption"
              :key="item.id"
              :value="item.id"
            >
              {{ item.planNum }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="加工单数量"
          hasFeedback
          prop="worksheetQuantity"
          style="width: 33%;float: left;"
        >
          <a-input
            :disabled="true"
            placeholder="请输入加工单数量"
            v-model.trim="model.worksheetQuantity"
          />
        </a-form-model-item>

        <a-form-model-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="备料数量"
          prop="pickListQuantity"
          style="width: 33%;float: left;"
        >
          <a-input-number
            style="width:100%"
            placeholder="请输入备料数量"
            v-model.trim="model.pickListQuantity"
            :min="1"
            :max="maxQuanCount"
            @change="handleSearch"
          />
        </a-form-model-item>

        <a-form-model-item
          label="创建日期"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          style="width: 33%;float: left;"
          prop="createDate"
        >
          <a-date-picker
            :showToday="false"
            placeholder="请选择创建日期"
            v-model.trim="model.createDate"
            @change="changeCreateDate"
            show-time
            type="date"
          />
        </a-form-model-item>
      </a-form-model>
    </a-card>

    <a-card class="card-content">
      <div
        :style="{
          width: '100%',
          background: '#fff',
        }"
      >
        <a-spin :spinning="confirmLoading" style="width: 100%;">
          <div class="formBox">
            <div class="requiredNews">商品信息</div>
            <a-table
              :columns="column"
              :data-source="tableData"
              :loading="loading"
              :pagination="pagination"
              @change="handleTableChange"
              bordered
            >
            </a-table>
          </div>
        </a-spin>

        <div style="text-align: center;">
          <a-button style="margin: 20px;" @click="cancel">取消</a-button>
          <a-button type="primary" @click="handleSubmit">保存</a-button>
        </div>
      </div>
      <!-- 
      <PickingAddModal
        :goodsList="goodsList"
        ref="modalForm"
        @ok="modalFormOk"
      ></PickingAddModal> -->
      <table-select-modal
        ref="selectForm"
        :columns="columns"
        :tableKey="tableKey"
        @tableSelect="tableSelect"
        :replaceFields="replaces"
        :code="code"
      ></table-select-modal>
    </a-card>
  </div>
</template>

<script>
import { column, columns } from "./components/tableConfig";
import { tableMinxins } from "@/unit/mixins/tableMinxins.js";
import TableSelectModal from "@/components/TableSelectModal";
import api from "@/api/apiServer";
export default {
  components: { TableSelectModal },
  mixins: [tableMinxins],
  data() {
    let validatePass = (rule, value, callback) => {
      if (value > this.maxQuanCount) {
        callback(new Error("备料数量已超过最大值"));
      } else {
        if (value === null || value === undefined || value === "") {
          callback(new Error("请输入加工单数量"));
        } else {
          callback();
        }
      }
    };
    return {
      columns,
      tableData: [],
      loading: false,
      pagination: false,
      wareHouseList: [], // 仓库列表

      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      rules: {
        pickListNum: [{ required: true, message: "请输入备料单号!" }],
        processOrderNum: [{ required: true, message: "请输入加工单号!" }],
        wareHouseId: [{ required: true, message: "请选择仓库!" }],
        pickListQuantity: [{ validator: validatePass, trigger: "change" }],
      },
      maxQuanCount: 99999,
      treeData: [],
      tableUserOption: [],
      columns,
      column,
      tableKey: "WorksheetList",
      code: "processNum",
      replaces: {},
      disabled: false,
    };
  },
  mounted() {
    if (this.$route.query.record) {
      this.model = JSON.parse(this.$route.query.record);
      if (this.model.goodsVOList) {
        this.tableData = this.model.goodsVOList;
      }
    } else {
      this.getNumber();
    }
    if (this.model.id) {
      this.disabled = true;
      this.bomId = this.model.bomId;
      this.getWorksheet(this.model.worksheetId);
    }
    this.getWareHouseList();
    this.getTypeList();
  },
  methods: {
    // 获取备料单号
    async getNumber() {
      const res = await api.PickListGetNumber();
      this.model.pickListNum = res.data;
    },
    // 时间格式化
    changeCreateDate(date, dateString) {
      this.model.createDate = dateString;
    },

    // 获取仓库列表
    async getWareHouseList() {
      var params = {};
      const res = await api.wareHouseList(params);
      this.wareHouseList = res.data;
    },
    //获取加工单数据
    async getWorksheet(id) {
      let params = { id, pageNumber: 1, pageSize: 10, deleteFlag: "N" };
      const res = await api.WorksheetList(params);
      this.tableUserOption = res.data.data;
    },

    // 删除
    async handleDelete(record) {
      var curIndex = 0;
      for (var i = 0; i < this.tableData.length; i++) {
        if (record.goodsCode == this.tableData[i].goodsCode) {
          curIndex = i;
        }
      }
      this.tableData.splice(curIndex, 1);
    },

    // 新增回调
    modalFormOk(data) {
      this.tableData.push(data);
    },

    // 确定
    async handleSubmit() {
      let res;
      this.confirmLoading = true;
      this.model.pickDetailLists = this.tableData;
      this.model.wareHouseNum = this.model.wareHouseId;
      //根据id判断是修改还是新增
      if (this.model.id) {
        res = await api.PickListUpdate(this.model); //修改
      } else {
        res = await api.PickListInsert(this.model); //新增
      }
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        this.confirmLoading = false;
        return;
      }
      this.$message.success(res.message);
      this.confirmLoading = false;
      this.$router.push("/picking");
    },

    // 取消
    cancel() {
      this.$router.push("/picking");
    },
    //仓库类型
    async getTypeList() {
      const res = await api.wareHouseTypeList();
      this.treeData = res.data;
      //对树形控件进行插槽设置
    },
    handleDepar() {
      this.$refs.selectForm.title = "加工单";
      this.$refs.selectForm.modalAdd();
      if (this.model.worksheetId) {
        let arr = this.model.worksheetId.toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs.selectForm.selectedRowKeys = newArr;
        } else {
          this.$refs.selectForm.selectedRowKeys = [];
        }
      }
    },
    tableSelect(result, tableUserOption) {
      this.tableUserOption = tableUserOption;
      this.$set(this.model, "worksheetId", result[0].id);
      this.$set(this.model, "worksheetNum", result[0].processNum);
      this.$set(this.model, "worksheetQuantity", result[0].productionQuantity);
      this.$set(this.model, "bomId", result[0].bomId);
      this.maxQuanCount = result[0].productionQuantity;
      this.$refs.ruleForm.clearValidate(["worksheetId"]);
      this.bomId = result[0].bomId;
      this.MaterialsPlan(result[0].productionQuantity);
    },
    handleDeparChange(value) {
      if (value.length > 0) {
        this.model.worksheetId = value.toString();
      } else {
        delete this.model.worksheetId;
      }
    },
    // 查询加工单用料
    async MaterialsPlan(planQuantity) {
      let params = {
        bomId: this.bomId,
        planQuantity,
      };
      if (planQuantity <= this.maxQuanCount) {
        const res = await api.worksheetPlan(params);
        const json = JSON.parse(
          JSON.stringify(res.data).replace(/planDemandQuantityNum/g, "amount")
        );
        this.tableData = json;
      }
    },
    handleSearch(value) {
      console.log(value, "1");
      console.log(this.bomId);
      if (
        value !== 0 &&
        this.bomId &&
        value !== "" &&
        value !== undefined &&
        value !== null
      ) {
        this.MaterialsPlan(value);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.card-header {
  margin: 20px 0;
}
.card-content {
  button {
    margin-right: 20px;
  }
}
.formBox {
  width: 100%;
  border: 1px solid #e9e9e9;
  padding: 10px 16px;
  margin: 18px 0;
  .requiredNews {
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 600;
    color: #1a5eff;
    margin-bottom: 12px;
  }

  .ant-calendar-picker {
    width: 100%;
  }
}
</style>
